package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.GreFileLogic;
import cn.topevery.garden.dal.logic.TaskDocumentLogic;
import cn.topevery.garden.dal.logic.TaskUserLogic;
import cn.topevery.garden.entity.dto.TaskDocumentDTO;
import cn.topevery.garden.entity.po.GreFile;
import cn.topevery.garden.entity.po.TaskDocument;
import cn.topevery.garden.entity.po.TaskUser;
import cn.topevery.garden.entity.query.TaskDocumentQuery;
import cn.topevery.garden.entity.vo.TaskDocumentVO;
import cn.topevery.garden.entity.vo.TaskUserVO;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.dal.logic.SysUserLogic;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

/**
 * 内业检查
 */
@Api(tags = "内业检查")
@RestController
@RequestMapping("/taskDocument")
public class TaskDocumentController extends BaseController {

    @Autowired
    private Mapper mapper;

    @Autowired
    TaskDocumentLogic taskDocumentLogic;

    @Autowired
    SysUserLogic sysUserLogic;

    @Autowired
    GreFileLogic greFileLogic;

    @Autowired
    TaskUserLogic taskUserLogic;

    /**
     * 获取内业检查分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取内业检查页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<TaskDocumentVO>> listPage(@RequestBody TaskDocumentQuery query) {

        if (Strings.isNotBlank(query.getCheckMonth())) {
            // 根据月份取月第一天和最后一天
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(query.getCheckMonth() + "-01", formatter);
            LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
            query.setBeginDate(String.valueOf(firstDayOfMonth));
            query.setEndDate(String.valueOf(lastDayOfMonth));
        }
        DataPager<TaskDocumentVO> page = taskDocumentLogic.listPage(query);
        for (TaskDocumentVO taskDocumentVO : page.records) {
            bindEvaluationUserList(taskDocumentVO.getId(), taskDocumentVO);
            bindFileList(taskDocumentVO.getId(), taskDocumentVO);
        }
        return JsonResult.ok(page);
    }

    @ApiOperation("新增/编辑 内业检查信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody TaskDocumentDTO dto) {
        String userId = getUser().id.toString();
        TaskDocument taskDocument = mapper.map(dto, TaskDocument.class);
        if (taskDocument.getScore() != null) {
            taskDocument.setFinished(true);
        }
        taskDocumentLogic.saveOrUpdate(userId, taskDocument);
        dto.setId(taskDocument.getId());
        // 删去旧的考评人员关联
        List<TaskUserVO> taskUserVOList = taskUserLogic.listByTaskTypeOrId(TaskUser.TYPE_TASK_DOCUMENT, dto.getId(), null);
        if (!taskUserVOList.isEmpty()) {
            Integer[] ids = taskUserVOList.stream().map(TaskUserVO::getId).toArray(Integer[]::new);
            taskUserLogic.deleteBatchById(userId, ids);
        }
        // 新增考评人员关联
        List<SysUser> evaluationUserList = dto.getEvaluationUserList();
        if (!CollectionUtils.isEmpty(evaluationUserList)) {
            List<TaskUser> taskUserList = new ArrayList<>();
            for (SysUser user : evaluationUserList) {
                TaskUser taskUser = new TaskUser();
                taskUser.taskId = dto.getId();
                taskUser.evaluationUserId = user.id;
                taskUser.taskType = TaskUser.TYPE_TASK_DOCUMENT;
                taskUserList.add(taskUser);
            }
            taskUserLogic.insert(userId, taskUserList);
        }


        // 删去旧的文件关联
        List<GreFile> oldFileList = greFileLogic.getListByMainId(dto.getId(), GreFile.TYPE_TASK_DOCUMENT);
        if (!CollectionUtils.isEmpty(oldFileList)) {
            Integer[] oldFileIdList = oldFileList.stream().map(GreFile::getId).toArray(Integer[]::new);
            greFileLogic.deleteBatchById(userId, oldFileIdList);
        }
        // 新增文件关联
        List<GreFile> newFileList = dto.getFileList();
        if (!CollectionUtils.isEmpty(newFileList)) {
            for (GreFile greFile : newFileList) {
                greFile.mainId = dto.getId();
                greFile.setDataType(GreFile.TYPE_TASK_DOCUMENT);
            }
            greFileLogic.insert(userId, newFileList);
        }

        return JsonResult.ok(true);
    }

    @ApiOperation("通过Id获取详情")
    @GetMapping("/getInfoById")
    public JsonResult<TaskDocumentVO> getInfoById(@RequestParam Integer id) {
        TaskDocument entity = taskDocumentLogic.getEntity(id);
        TaskDocumentVO vo = mapper.map(entity, TaskDocumentVO.class);
        bindEvaluationUserList(id, vo);
        bindFileList(id, vo);
        return JsonResult.ok(vo);
    }

    /**
     * 绑定文件列表
     *
     * @param taskId 任务ID
     * @param vo     考评详情
     */
    private void bindFileList(Integer taskId, TaskDocumentVO vo) {
        List<GreFile> fileList = greFileLogic.getListByMainId(taskId, GreFile.TYPE_TASK_DOCUMENT);
        // 绑定填报附件
        fileList.addAll(greFileLogic.getListByMainId(taskId, GreFile.TYPE_TASK_DOCUMENT));
        vo.setFileList(fileList);
    }

    /**
     * 绑定考评人员
     *
     * @param taskId 任务ID
     * @param vo     考评详情
     */
    private void bindEvaluationUserList(Integer taskId, TaskDocumentVO vo) {
        List<TaskUserVO> taskUserVOS = taskUserLogic.listByTaskTypeOrId(TaskUser.TYPE_TASK_DOCUMENT, taskId, null);
        Integer[] userIds = taskUserVOS.stream().map(TaskUserVO::getEvaluationUserId).toArray(Integer[]::new);
        List<SysUser> userList = sysUserLogic.getEntitys(userIds);
        List<SysUser> res = new ArrayList<>();
        for (SysUser user : userList) {
            SysUser resUser = new SysUser();
            resUser.id = user.id;
            resUser.userId = user.userId;
            resUser.userName = user.userName;
            res.add(resUser);
        }
        vo.setEvaluationUserList(res);
    }

    @ApiOperation("根据自增ID批量删除")
    @PostMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestBody Integer[] ids) {
        taskDocumentLogic.deleteBatchById(getUser().id.toString(), ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出内业检查信息")
    @GetMapping("/export")
    public void export(TaskDocumentQuery query, HttpServletResponse response) {
        List<TaskDocumentVO> list = taskDocumentLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "内业检查", "sheet1", TaskDocumentVO.class, "内业检查", response);
    }

    @ApiOperation("获得我的任务或已填报")
    @GetMapping("listMyTask")
    public JsonResult listMyTask(TaskDocumentQuery query) {
        SysUser user = getUser();
        query.setTaskOwnerId(user.id);
        DataPager<TaskDocumentVO> page = taskDocumentLogic.pageMyTask(query);
        return JsonResult.ok(page);
    }

    @ApiOperation("填报我的任务")
    @PostMapping("saveMyTask")
    public JsonResult saveMyTask(@RequestBody TaskDocumentVO taskDocumentVO) {
        TaskDocument taskDocument = taskDocumentLogic.getEntity(taskDocumentVO.getId());
        taskDocument.setCheckTime(taskDocumentVO.getCheckTime());
        taskDocument.setScore(taskDocumentVO.getScore());
        taskDocument.setEvaluationContent(taskDocumentVO.getEvaluationContent());
        taskDocument.setCheckTime(LocalDateTime.now());
        taskDocument.setFinished(true);
        taskDocumentLogic.saveOrUpdate(getUserId(), taskDocument);
        return JsonResult.ok();
    }

    @ApiOperation("删除我的填报")
    @GetMapping("deleteMyFinished")
    public JsonResult deleteMyFinished(TaskDocumentVO taskDocumentVO) {
        String userId = getUserId();
        TaskDocument taskDocument = taskDocumentLogic.getEntity(taskDocumentVO.getId());
        taskDocument.setScore(null);
        taskDocument.setEvaluationContent(null);
        taskDocument.setCheckTime(null);
        taskDocument.setFinished(false);
        taskDocumentLogic.saveOrUpdate(userId, taskDocument);
        return JsonResult.ok();
    }

}
